from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import Http404
from .models import BlogPost
from .forms import BlogPostForm

# Create your views here.
#显示主页
def home(request):
    '''显示主页'''
    return render(request, 'blogs/home.html')
#检查博客所有者
def check_blog_owner(request, blog):
    '''检查博客所有者'''
    if blog.owner != request.user:
        raise Http404

#显示所有博客
@login_required
def blogs(request):
    '''显示所有博客'''
    blogs = BlogPost.objects.filter(owner=request.user).order_by('-date_added')
    context = {'blogs': blogs}
    return render(request, 'blogs/blogs.html', context)

#显示特定博客
@login_required
def blog(request, blog_id):
    '''显示特定博客'''
    blog = BlogPost.objects.get(id=blog_id)
    check_blog_owner(request, blog) #检查博客所有者
    context = {'blog': blog}
    return render(request, 'blogs/blog.html', context)

#添加博客
@login_required
def new_blog(request):
    '''添加博客'''
    if request.method != 'POST':
        #未提交数据：创建一个新表单
        form = BlogPostForm()
    else:
        #POST提交的数据，对数据进行处理
        form = BlogPostForm(data=request.POST)
        if form.is_valid():
            new_blog = form.save(commit=False)
            new_blog.owner = request.user
            new_blog.save()
            return redirect('blogs:blogs')
    return render(request, 'blogs/new_blog.html', {'form': form})

#编辑博客
@login_required
def edit_blog(request, blog_id):
    '''编辑博客'''
    blog = BlogPost.objects.get(id=blog_id)
    check_blog_owner(request, blog) #检查博客所有者
    if request.method != 'POST':
        #初次请求，使用当前条目填充表单
        form = BlogPostForm(instance=blog)
    else:
        #POST提交的数据，对数据进行处理
        form = BlogPostForm(instance=blog, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('blogs:blog', blog_id=blog_id)
    context = {'blog': blog, 'form': form}
    return render(request, 'blogs/edit_blog.html', context)